package com.chuji.crmcj.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.ClientDetailAct;
import com.chuji.crmcj.act.DataCompleteActivity;
import com.chuji.crmcj.bean.ReceiveEndTaskInfo;
import com.chuji.crmcj.bean.ReceiveStandCompleteTaskInfo;
import com.chuji.crmcj.utils.NumberUtils;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.util.ArrayList;
import java.util.List;


public class ReceiveTaskFragment extends Fragment {
    /*待接待客户*/
    private ListView lv_stand_receive_task;
    /*待接待数据存储*/
    List<ReceiveStandCompleteTaskInfo.ApiParamObjEntity> receiveStandCompleteTaskData;
    /*待接待网络数据*/
    private ReceiveStandCompleteTaskInfo receiveStandCompleteTaskInfo;
    /*待完善客户*/
    private LinearLayout ll_stand_follow_client;
    private ListView lv_received_no_complete;
    /*已完成客户*/
    private LinearLayout ll_end_task;
    private ListView lv_completed_client;
    /*已完成数据存储*/
    List<ReceiveEndTaskInfo.ApiParamObjEntity> receiveEndTaskData;
    /*已完成网络数据*/
    private ReceiveEndTaskInfo receiveEndTaskInfo;
    /*自定义适配器*/
    private CustomStandCompleteAdapter customStandCompleteAdapter;

    private CustomReceiveAdapter customReceiveAdapter;
    //没有数据显示页面
    private LinearLayout ll_noData;
    private ScrollView scrollView;
    View comsumView;
    View chargeView;
    //销售员ID
    String SalesID;
    //销售员ID
    String FlowID;
    //销售员ID
    String CustomerID;
    //销售员ID
    String OriginalSalesID;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_receive_task, container,  false);
        lv_stand_receive_task = (ListView) view.findViewById(R.id.lv_stand_receive_task);
        lv_completed_client= (ListView) view.findViewById(R.id.lv_completed_client);
        ll_stand_follow_client= (LinearLayout) view.findViewById(R.id.ll_stand_follow_client);
        ll_end_task= (LinearLayout) view.findViewById(R.id.ll_end_task);
        ll_noData=(LinearLayout) view.findViewById(R.id.ll_noData);
//        scrollView= (ScrollView) view.findViewById(R.id.scrollView);
        //请求数据
        initData();
        //初始化适配器
        customStandCompleteAdapter=new CustomStandCompleteAdapter();
        customReceiveAdapter=new CustomReceiveAdapter();
        //填充
        lv_stand_receive_task.setAdapter(customStandCompleteAdapter);
        setListViewHeightBasedOnChildren(lv_stand_receive_task);
        lv_completed_client.setAdapter(customReceiveAdapter);
        setListViewHeightBasedOnChildren(lv_completed_client);
//        //给ListView设置点击事件
//        lv_stand_receive_task.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                UIUtils.startActivity(new Intent(UIUtils.getContext(), DataCompleteActivity.class));
//            }
//        });
//        //给ListView设置点击事件
//        lv_completed_client.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                UIUtils.startActivity(new Intent(UIUtils.getContext(), ClientDetailAct.class));
//            }
//        });
        return view;
    }

    private void initData() {
        /**
         * 获得待接待任务信息
         */
        getStandCompTaskData();
        /**
         * 获得已完成任务信息
         */
        getEndTaskData();
        //显示无数据界面
        if(ll_stand_follow_client.getVisibility()==View.GONE&&ll_end_task.getVisibility()==View.GONE){
//            scrollView.setVisibility(View.GONE);
            ll_noData.setVisibility(View.VISIBLE);
        }else{
            ll_noData.setVisibility(View.GONE);
        }

    }
    private void getStandCompTaskData() {
        //第一次
        if (receiveStandCompleteTaskData == null) {
            receiveStandCompleteTaskData = new ArrayList<ReceiveStandCompleteTaskInfo.ApiParamObjEntity>();
        }
        requestStandData();
    }
    private void requestStandData() {
        //初始化Volley
        SalesID= SPUtils.getString(UIUtils.getContext(),"UserID","");
        String strURL = String.format(UrlUtils.STAND_COMPLETE_TASK+"&SalesID="+SalesID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                receiveStandCompleteTaskInfo = JSON.parseObject(response, ReceiveStandCompleteTaskInfo.class);
                receiveStandCompleteTaskData.addAll(receiveStandCompleteTaskInfo.getApiParamObj());
                if(receiveStandCompleteTaskInfo.getApiParamObj().size()==0){
                    ll_stand_follow_client.setVisibility(View.GONE);
                }else {
                    UIUtils.runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            // 判断adapter是否创建
                            if (customStandCompleteAdapter == null) {
                                customStandCompleteAdapter = new CustomStandCompleteAdapter();
                                lv_stand_receive_task.setAdapter(customStandCompleteAdapter);
                                setListViewHeightBasedOnChildren(lv_stand_receive_task);
                            } else {
                                customStandCompleteAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    private void getEndTaskData() {
        //第一次
        if (receiveEndTaskData == null) {
            receiveEndTaskData = new ArrayList<ReceiveEndTaskInfo.ApiParamObjEntity>();
        }
        requestEndTaskData();
    }
    private void requestEndTaskData() {
        //初始化Volley
        SalesID=SPUtils.getString(UIUtils.getContext(), "UserID", "");
        String strURL = String.format(UrlUtils.END_TASK+"&SalesID="+SalesID);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                receiveEndTaskInfo = JSON.parseObject(response, ReceiveEndTaskInfo.class);
                receiveEndTaskData.addAll(receiveEndTaskInfo.getApiParamObj());
                if(receiveEndTaskInfo.getApiParamObj().size()==0){
                    ll_end_task.setVisibility(View.GONE);
                }else {
                    UIUtils.runInMainThread(new Runnable() {
                        @Override
                        public void run() {
                            // 判断adapter是否创建
                            if (customReceiveAdapter == null) {
                                customReceiveAdapter = new CustomReceiveAdapter();
                                lv_completed_client.setAdapter(customReceiveAdapter);
                                setListViewHeightBasedOnChildren(lv_completed_client);
                            } else {
                                customReceiveAdapter.notifyDataSetChanged();
                            }
                        }
                    });
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    /**
     * 自定义适配器
     */
    class CustomStandCompleteAdapter extends BaseAdapter {
        private static final int TYPE_COUNT = 2;//item类型的总数
        private static final int TYPE_COMSUM = 0;//新进店客户
        private static final int TYPE_CHARGE = 1;//已有客户
        private Context mContext;
        private int currentType;//当前item类型
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return receiveStandCompleteTaskData.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return receiveStandCompleteTaskData.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public int getItemViewType(int position) {
            // TODO Auto-generated method stub
            if (receiveStandCompleteTaskData.get(position).getCustomerID()==null) {
                return TYPE_COMSUM;// 新进店客户
            } else if (receiveStandCompleteTaskData.get(position).getOriginalSalesID()!=null) {
                return TYPE_CHARGE;// 已有客户
            } else {
                return 100;
            }
        }

        @Override
        public int getViewTypeCount() {
            return TYPE_COUNT;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub


            currentType = getItemViewType(position);
            if (currentType == TYPE_COMSUM) {
                NewClentViewHolder comsumHolder = null;
                if (convertView == null) {
                    comsumHolder = new NewClentViewHolder();
                    comsumView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_stand_perfect_go, null);
                    comsumHolder.tv_client_num = (TextView) comsumView.findViewById(R.id.tv_client_num);
                    comsumHolder.iv_keliu_tag = (ImageView) comsumView.findViewById(R.id.iv_keliu_tag);
                    comsumHolder.iv_toushu_tag = (ImageView) comsumView.findViewById(R.id.iv_toushu_tag);
                    comsumHolder.tv_time = (TextView) comsumView.findViewById(R.id.tv_time);

                    comsumView.setTag(comsumHolder);
                    convertView = comsumView;
                } else {
                    comsumHolder = (NewClentViewHolder) convertView.getTag();
                }
                comsumHolder.tv_client_num.setText(receiveStandCompleteTaskData.get(position).getCustomerCount());//进店人数
                //隐藏客流图标
                comsumHolder.iv_keliu_tag.setVisibility(View.INVISIBLE);
                //判断催促次数和是否投诉
                if(receiveStandCompleteTaskData.get(position).getUrgeCount()=="0"){
                    comsumHolder.iv_toushu_tag.setVisibility(View.INVISIBLE);
                }else if(receiveStandCompleteTaskData.get(position).getUrgeCount()=="1"){
                    comsumHolder.iv_toushu_tag.setImageResource(R.drawable.cuicuone);
                }else if(receiveStandCompleteTaskData.get(position).getUrgeCount()=="2"){
                    comsumHolder.iv_toushu_tag.setImageResource(R.drawable.cuicutwo);
                }else if(receiveStandCompleteTaskData.get(position).getComplaint()!=null){
                    comsumHolder.iv_toushu_tag.setImageResource(R.drawable.toushu);
                }
                //判断跳转
                lv_stand_receive_task.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent=new Intent(UIUtils.getContext(), DataCompleteActivity.class);
                        intent.putExtra("FlowID",receiveStandCompleteTaskData.get(position).getFlowID());
                        intent.putExtra("CustomerID", receiveStandCompleteTaskData.get(position).getCustomerID());
                        startActivity(intent);
                    }
                });
            } else if (currentType == TYPE_CHARGE) {
                OldClientViewHolder chargeHoler;
                if (convertView == null) {
                    chargeHoler = new OldClientViewHolder();
                    chargeView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_end_task, null);
                    chargeHoler.tv_client_name = (TextView) chargeView.findViewById(R.id.tv_client_name);
                    chargeHoler.iv_client_tag = (ImageView) chargeView.findViewById(R.id.iv_client_tag);
                    chargeHoler.tv_car_type = (TextView) chargeView.findViewById(R.id.tv_car_type);
                    chargeHoler.tv_client_phoneNumber = (TextView) chargeView.findViewById(R.id.tv_client_phoneNumber);
                    chargeHoler.tv_handle_time = (TextView) chargeView.findViewById(R.id.tv_handle_time);
                    chargeHoler.ll_end_task= (LinearLayout) chargeView.findViewById(R.id.ll_end_task);
                    chargeView.setTag(chargeHoler);
                    convertView = chargeView;
                } else {
                    chargeHoler = (OldClientViewHolder) convertView.getTag();
                }
                if(receiveStandCompleteTaskData.size()!=0) {
                    chargeHoler.tv_client_name.setText(receiveStandCompleteTaskData.get(position).getName());// 客户名称
                    if (receiveStandCompleteTaskData.get(position).getTel().length() == 11) {
                        chargeHoler.tv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(receiveStandCompleteTaskData.get(position).getTel()));// 客户号码
                    } else {
                        chargeHoler.tv_client_phoneNumber.setText(receiveStandCompleteTaskData.get(position).getTel());
                    }
                    chargeHoler.tv_car_type.setText(receiveStandCompleteTaskData.get(position).getCarModel());//车型
                    chargeHoler.tv_handle_time.setText(receiveStandCompleteTaskData.get(position).getEnterTime());//时间
                    lv_stand_receive_task.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(UIUtils.getContext(), DataCompleteActivity.class);
                            intent.putExtra("FlowID", receiveStandCompleteTaskData.get(position).getFlowID());
                            intent.putExtra("CustomerID", receiveStandCompleteTaskData.get(position).getCustomerID());
                            intent.putExtra("OriginalSalesID", receiveStandCompleteTaskData.get(position).getOriginalSalesID());
                            startActivity(intent);
                        }
                    });
                }else {
                    UIUtils.showToastSafe("暂无数据");
                }
            }
            return convertView;
        }
        /**
         * 新进店客户
         * @author yl
         *
         */
        class NewClentViewHolder {
            TextView tv_client_num;
            ImageView iv_keliu_tag;
            ImageView iv_toushu_tag;
            TextView tv_time;
            LinearLayout ll_stand_task;
        }

        /**
         * 已有客户
         * @author yl
         *
         */
        class OldClientViewHolder {
            TextView tv_client_name;
            ImageView iv_client_tag;
            TextView tv_car_type;
            TextView tv_client_phoneNumber;
            TextView tv_handle_time;
            LinearLayout ll_end_task;
        }
    }
    class CustomReceiveAdapter extends BaseAdapter {

        private static final int TYPE_COUNT = 2;//item类型的总数
        private static final int TYPE_COMSUM = 0;//已完成客户
        private static final int TYPE_CHARGE = 1;//客流客户
        private Context mContext;
        private int currentType;//当前item类型
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return receiveEndTaskData.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return receiveEndTaskData.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        @Override
        public int getItemViewType(int position) {
            // TODO Auto-generated method stub
            if ("0".equals(receiveEndTaskData.get(position).isIsProfile())) {
                return TYPE_COMSUM;// 已完成客户
            } else if ("1".equals(receiveEndTaskData.get(position).isIsProfile())) {
                return TYPE_CHARGE;// 客流客户
            } else {
                return 100;
            }
        }

        @Override
        public int getViewTypeCount() {
            return TYPE_COUNT;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View comsumView = null;
            View chargeView = null;

            currentType = getItemViewType(position);
            if (currentType == TYPE_COMSUM) {
                NewClentViewHolder comsumHolder = null;
                if (convertView == null) {
                    comsumHolder = new NewClentViewHolder();
                    comsumView = LayoutInflater.from(mContext).inflate(R.layout.listview_stand_perfect_go, null);
                    comsumHolder.tv_client_num = (TextView) comsumView.findViewById(R.id.tv_client_num);
                    comsumHolder.iv_keliu_tag = (ImageView) comsumView.findViewById(R.id.iv_keliu_tag);
                    comsumHolder.iv_toushu_tag = (ImageView) comsumView.findViewById(R.id.iv_toushu_tag);
                    comsumHolder.tv_time = (TextView) comsumView.findViewById(R.id.tv_time);
                    comsumView.setTag(comsumHolder);
                    convertView = comsumView;
                } else {
                    comsumHolder = (NewClentViewHolder) convertView.getTag();
                }
                comsumHolder.tv_client_num.setText(receiveEndTaskData.get(position).getCustomerCount());//进店人数
                //判断是否是客流客户
                if(receiveEndTaskData.get(position).isIsProfile()=="0"){
                    comsumHolder.iv_keliu_tag.setVisibility(View.INVISIBLE);
                }else{
                    comsumHolder.iv_keliu_tag.setVisibility(View.VISIBLE);
                }
                //隐藏催促图标
                comsumHolder.iv_toushu_tag.setVisibility(View.INVISIBLE);
                comsumHolder.ll_stand_task.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UIUtils.showToastSafe("客流客户");
                    }
                });
            } else if (currentType == TYPE_CHARGE) {
                OldClientViewHolder chargeHoler = null;
                if (convertView == null) {
                    chargeHoler = new OldClientViewHolder();
                    chargeView = LayoutInflater.from(mContext).inflate(R.layout.listview_end_task, null);
                    chargeHoler.tv_client_name = (TextView) chargeView.findViewById(R.id.tv_client_name);
                    chargeHoler.iv_client_tag = (ImageView) chargeView.findViewById(R.id.iv_client_tag);
                    chargeHoler.tv_car_type = (TextView) chargeView.findViewById(R.id.tv_car_type);
                    chargeHoler.tv_client_phoneNumber = (TextView) chargeView.findViewById(R.id.tv_client_phoneNumber);
                    chargeHoler.tv_handle_time = (TextView) chargeView.findViewById(R.id.tv_handle_time);
                    chargeView.setTag(chargeHoler);
                    convertView = chargeView;
                } else {
                    chargeHoler = (OldClientViewHolder) convertView.getTag();
                }
                if(receiveEndTaskData.size()!=0) {
                    chargeHoler.tv_client_name.setText(receiveEndTaskData.get(position).getName());// 客户名称
                    if (receiveEndTaskData.get(position).getTel().length() == 11) {
                        chargeHoler.tv_client_phoneNumber.setText(NumberUtils.parsePhoneNumber(receiveEndTaskData.get(position).getTel()));// 客户号码
                    } else {
                        chargeHoler.tv_client_phoneNumber.setText(receiveEndTaskData.get(position).getTel());
                    }
                    chargeHoler.tv_car_type.setText(receiveEndTaskData.get(position).getCarModel());//车型
                    chargeHoler.tv_handle_time.setText(receiveEndTaskData.get(position).getEnterTime());//时间
//                    chargeHoler.ll_end_task.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                        }
//                    });
                    lv_completed_client.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(UIUtils.getContext(), ClientDetailAct.class);
                            intent.putExtra("FlowID", receiveEndTaskData.get(position).getFlowID());
                            intent.putExtra("OriginalSalesID", receiveEndTaskData.get(position).getOriginalSalesID());
                            startActivity(intent);
                        }
                    });
                }else {
                    UIUtils.showToastSafe("暂无数据");
                }
            }
            return convertView;
        }
        /**
         * 客流客户
         * @author yl
         *
         */
        class NewClentViewHolder {
            TextView tv_client_num;
            ImageView iv_keliu_tag;
            ImageView iv_toushu_tag;
            TextView tv_time;
            LinearLayout ll_stand_task;
        }

        /**
         * 已完成客户
         * @author yl
         *
         */
        class OldClientViewHolder {
            TextView tv_client_name;
            ImageView iv_client_tag;
            TextView tv_car_type;
            TextView tv_client_phoneNumber;
            TextView tv_handle_time;
            LinearLayout ll_end_task;
        }
    }
    //手动设置Listview的高度
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
